package com.wt.admin.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.wt.admin.config.cache.Cache;
import com.wt.admin.domain.ConstVar;
import com.wt.admin.domain.dom.SessionCodeDO;
import com.wt.admin.domain.entity.sys.SysSettingEntity;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RequestMapping("index")
@RestController
@Slf4j
public class IndexController {

    @Resource
    private Cache<String, SysSettingEntity> settingCache;
    @Resource
    private Cache<String, SessionCodeDO> sessionCodeCache;

    @PostMapping("code")
    public void generateCaptcha(HttpServletRequest request,HttpServletResponse response) throws IOException {
        response.setContentType("image/png");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Content-Disposition", "inline");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(120, 30, 4, 3);
        SysSettingEntity.Application application = settingCache.get(ConstVar.SettingModel.SETTING).getApplication();
        response.setHeader("sessionId",application.getKey());
        response.setHeader("seed",String.valueOf(application.getSeed()));
        String id = request.getSession().getId();
        response.setHeader("id", id);
        sessionCodeCache.put(id,SessionCodeDO.builder()
                .id(id).code(captcha.getCode().toLowerCase())
                .time(System.currentTimeMillis() + 1000 * 60)
                .build()
        );
        captcha.write(response.getOutputStream());
    }

}
